package SaveServlet.manager;

import com.lyq.bean.Course;
import com.lyq.bean.Major;
import com.lyq.bean.Year;
import com.lyq.bean.mySql.CourseDAO;
import com.lyq.bean.mySql.Major_Sql;
import com.lyq.bean.mySql.Year_Sql;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/batchRequiredCourse")
public class BatchRequiredCourseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    private void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 获取筛选参数
        String majorIdParam = request.getParameter("majorId");
        String yearIdParam = request.getParameter("yearId");

        Integer majorId = null;
        Integer yearId = null;

        try {
            if (majorIdParam != null && !majorIdParam.isEmpty()) {
                majorId = Integer.parseInt(majorIdParam);
            }
            if (yearIdParam != null && !yearIdParam.isEmpty()) {
                yearId = Integer.parseInt(yearIdParam);
            }
        } catch (NumberFormatException e) {
            // 处理参数格式错误
            request.setAttribute("errorMessage", "参数格式错误");
        }

        try {
            // 获取专业列表
            List<Major> majors = Major_Sql.getAllMajors();
            System.out.println("3333");
            request.setAttribute("majors", majors);

            // 获取届数列表
            List<Year> years = Year_Sql.getAllYears();
            request.setAttribute("years", years);

            // 根据筛选条件获取课程列表
            List<Course> courses;
            if (majorId != null || yearId != null) {
                // 根据专业和届数筛选课程
                courses = CourseDAO.getRequiredCoursesByMajorAndYear(majorId, yearId);
            } else {
                // 获取所有必修课程
                courses = CourseDAO.getAllRequiredCourses();
            }
            request.setAttribute("courses", courses);

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("errorMessage", "数据加载失败: " + e.getMessage());
        }

        // 转发到JSP页面
        RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/manager/BatchRequiredCourse.jsp");
        dispatcher.forward(request, response);
    }
}

